//
//  PTLogin.swift
//  PointTest28
//
//  Created by sc-chen on 2023/6/21.
//

import SwiftUI

struct PTLogin: View {
#if DEBUG
    @State private var username = "test"
    @State private var password = "bdsh@123*"
#else
    @State private var username = ""
    @State private var password = ""
#endif
    @State var isChecked: Bool = false
    @State var showAlert: Bool = false
    
    @State var canNext: Bool = false
    @State private var isShowingHUD = false
    @State private var detailTxt = "请稍后..."
    
    @AppStorage("isLoggedIn") var isLoggedIn = false
    
    var body: some View {
        ZStack {
            ScrollView {
                Image("bg_login_login")
                    .resizable()
                    .frame(maxWidth: .infinity,maxHeight: 125)
                
                Image("login_logo")
                    .frame(width: 60, height: 60)
                    .clipShape(Circle())
                    .offset(y: -45)
                VStack {
                    TextField("请输入账号", text: $username)
                        .overlay(
                            RoundedRectangle(cornerRadius: 25)
                                .stroke(Color.gray, lineWidth: 1)
                        )
                        .padding(.leading,10)
                        .padding(.trailing,10)
                        .padding(.bottom,10)
                        .submitLabel(.done)
                        .foregroundColor(.black)
                    
                    SecureField("请输入密码", text: $password)
                        .overlay(
                            RoundedRectangle(cornerRadius: 25)
                                .stroke(Color.gray, lineWidth: 1)
                        )
                        .padding(.leading,10)
                        .padding(.trailing,10)
                        .submitLabel(.done)
                        .foregroundColor(.black)
                    
                    HStack {
                        Button(action: { isChecked.toggle() }) {
                            Image(systemName: isChecked ? "checkmark.square.fill" : "square")
                                .foregroundColor(.blue)
                        }
                        .frame(width: 17,height: 17)
                        
                        Text("勾选即同意")
                            .font(.system(size: 14))
                            .foregroundColor(.black)
                        Text("《用户协议》")
                            .foregroundColor(.blue)
                            .font(.system(size: 14))
                    }
                    .padding(.top,10)
                    
                    Text("和")
                        .font(.system(size: 14))
                        .foregroundColor(.black)
                        .padding(.bottom,1)
                    Text("《隐私政策》")
                        .foregroundColor(.blue)
                        .font(.system(size: 14))
                        .padding(.bottom,20)
                    
                    Button {
                        if isChecked {
                            login()
                        }else{
                            self.showAlert.toggle()
                        }
                    } label: {
                        Text("登录")
                            .foregroundColor(.white)
                            .padding()
                            .frame(maxWidth: .infinity,maxHeight: 50)
                            .background(
                                RoundedRectangle(cornerRadius: 25)
                                    .fill(Color.blue)
                                    .padding(.leading, 10)
                                    .padding(.trailing, 10)
                            )
                            .alert(isPresented: $showAlert) {
                                Alert(title: Text("提示"), message: Text("请勾选用户协议和隐私政策"), dismissButton: .default(Text("好的")))
                            }
                    }
                }
                Spacer()
            }
            PTProgressHud(isPresented: $isShowingHUD, text: $detailTxt)
        }
        .navigationBarTitleDisplayMode(.inline)
        .background(Color.white)
    }
    
    func login() -> Void {
        self.isShowingHUD = true
        // 创建一个URL对象
        guard let url = URL(string: "http://115.28.129.60:8382/management/admin/login") else {
            print("Invalid URL")
            return
        }
        
        let body: [String: Any] = [
            "username": username,
            "password": password,
            "id": "ToolID02",
            "version": "1.0"
        ]
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: body)
        } catch {
            print("无效的请求体")
            return
        }
        
        // 创建URLSession对象，并发送请求
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            
            guard let data = data else {
                print("No data")
                return
            }
            
            do {
                // 将Data对象转换为JSON对象
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                
                // 使用转换后的JSON对象
                if let jsonDictionary = json as? [String: Any] {
                    let code = jsonDictionary["code"] as? Int ?? 0
                    if code == 0000 {
                        canNext = true
                        isShowingHUD = false
                        UserAuth().login()
                    }
                }
            } catch {
                print("转换失败：\(error.localizedDescription)")
                detailTxt = "请求失败!"
                DispatchQueue.main.asyncAfter(deadline: .now()+2){
                    isShowingHUD = false
                }
            }
        }.resume()
    }
}


struct PTLogin_Previews: PreviewProvider {
    static var previews: some View {
        PTLogin()
    }
}
